package com.wt.admin.service.sys.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wt.admin.code.sys.SysMenu1200;
import com.wt.admin.domain.entity.sys.SysMenuEntity;
import com.wt.admin.mapper.sys.SysMenuMapper;
import com.wt.admin.service.sys.SysMenuService;
import com.wt.admin.util.AssertUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements SysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenuEntity> find(SysMenuEntity data) {
        List<SysMenuEntity> menus = sysMenuMapper.selectAll();
        List<SysMenuEntity> newMenu = new ArrayList<>();
        toTree(menus,newMenu,0);
        return newMenu;
    }

    @Override
    public SysMenuEntity edit(SysMenuEntity data) {
        AssertUtil.objIsNull(data.getMenuName(), SysMenu1200.MENU_CODE_1200);
        AssertUtil.objIsNull(data.getPath(), SysMenu1200.MENU_CODE_1201);
        if(ObjectUtil.isEmpty(data.getParent())){
            data.setParent(0);
        }
        saveOrUpdate(data);
        return data;
    }

    @Override
    public List<SysMenuEntity> findMenu(List<Integer> menuIds,boolean toTree) {
        List<SysMenuEntity> menus = sysMenuMapper.findByIds(menuIds);
        List<SysMenuEntity> newMenu = new ArrayList<>();
        if(toTree){
            toTree(menus,newMenu,0);
            menus = newMenu;
        }
        return menus;
    }

    @Override
    public SysMenuEntity del(SysMenuEntity data) {
        AssertUtil.objIsNull(data.getId(), SysMenu1200.MENU_CODE_1202);
        sysMenuMapper.deleteById(data.getId());
        return null;
    }

    private void toTree(List<SysMenuEntity> menus,List<SysMenuEntity> newMenu,Integer parent){
        boolean b = menus.stream().anyMatch(i -> parent.equals(i.getParent()));
        if(!b){
            return;
        }
        menus.stream().forEach(i -> {
            if(!parent.equals(i.getParent())){
                return;
            }
            newMenu.add(i);
            List<SysMenuEntity> children = i.getChildren();
            toTree(menus,children,i.getId());
        });
    }

}
